const jwt = require('jsonwebtoken');
const User = require('../models/User');

/**
 * JWT认证中间件
 * 验证请求头中的token，并将用户信息添加到req.user中
 */
const authenticateToken = async (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '访问被拒绝，需要提供认证token',
        data: null
      });
    }

    // 验证token
    const jwtSecret = process.env.JWT_SECRET || 'your-secret-key';
    const decoded = jwt.verify(token, jwtSecret);

    // 从数据库获取用户信息
    const user = await User.findByUserId(decoded.sub);
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: '用户不存在或已被删除',
        data: null
      });
    }

    // 将用户信息添加到请求对象中
    req.user = {
      userId: user.userId,
      email: user.email,
      nickName: user.nickName,
      avatar: user.avatar,
      status: user.status
    };

    next();
  } catch (error) {
    console.error('Token验证失败:', error);
    
    if (error.name === 'JsonWebTokenError') {
      return res.status(401).json({
        code: 401,
        message: '无效的token',
        data: null
      });
    }
    
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({
        code: 401,
        message: 'token已过期',
        data: null
      });
    }

    return res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      data: null
    });
  }
};

/**
 * 可选的认证中间件
 * 如果提供了token则验证，否则继续执行（用于可选登录的接口）
 */
const optionalAuth = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      req.user = null;
      return next();
    }

    const jwtSecret = process.env.JWT_SECRET || 'your-secret-key';
    const decoded = jwt.verify(token, jwtSecret);
    
    const user = await User.findByUserId(decoded.sub);
    if (user) {
      req.user = {
        userId: user.userId,
        email: user.email,
        nickName: user.nickName,
        avatar: user.avatar,
        status: user.status
      };
    } else {
      req.user = null;
    }

    next();
  } catch (error) {
    // 可选认证失败时不阻止请求继续
    req.user = null;
    next();
  }
};

module.exports = {
  authenticateToken,
  optionalAuth
};